package com.bigmodel.util;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 调用ChatGPT接口
 */
public class OpeAI {
    final String AK = "Bearer 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";
//    private static final String API_ENDPOINT = "https://api.openai.com/v1/chat/completions";
    private static final String API_ENDPOINT = "https://api-test.237224320.workers.dev/v1/chat/completions";
//    private static final String API_ENDPOINT = "https://api-proxy-openai.itwk.cc";
    private static final String API_KEY = "Bearer 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";
//    private static final String API_KEY = "Bearer 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";

    public String chat(String prompt){
        RestTemplate restTemplate = new RestTemplate();


        SimpleClientHttpRequestFactory simpleClientHttpRequestFactory = new SimpleClientHttpRequestFactory();
        simpleClientHttpRequestFactory.setProxy(new Proxy(Proxy.Type.HTTP,new InetSocketAddress("127.0.0.1",33210))); // 添加代理 ip 和 port 即可
        restTemplate.setRequestFactory(simpleClientHttpRequestFactory);

        //构造请求头l
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.set("Content-Type","application/json");
        httpHeaders.set("Authorization",API_KEY);


        //构造请求体
        ChatGptRequestModel requestModel = builderChatGptRequestModel(prompt);
        String s = JSONObject.toJSONString(requestModel);
        HttpEntity<ChatGptRequestModel> entity = new HttpEntity(s, httpHeaders);

        //获取响应体
        JSONObject json = null;
        ChatGPTResponseModel chatGPTResponseModel = null;
        try{
            ResponseEntity<String> jsonObjectResponseEntity = restTemplate.postForEntity(API_ENDPOINT,
                    entity, String.class);
            if(!StringUtils.isEmpty(jsonObjectResponseEntity.getBody()) ){
                chatGPTResponseModel = JSONObject.parseObject(jsonObjectResponseEntity.getBody(), ChatGPTResponseModel.class);
            }
            System.out.println(jsonObjectResponseEntity.getBody());
//          chatGPTResponseModel = jsonObjectResponseEntity.getBody().toJavaObject(ChatGPTResponseModel.class);
        }catch (Exception e){
            e.printStackTrace();
        }
        String res = null;
        if(chatGPTResponseModel == null){
            return res;
        }
        //解析响应结果
        List<ResponseChoicesModel> choices = chatGPTResponseModel.getChoices();
        if(!ObjectUtils.isEmpty(choices)){
            ResponseChoicesModel responseChoicesModel = choices.get(0);
            MessageModel message = responseChoicesModel.getMessage();
            if(message != null){
                res = message.getContent();
            }
        }

        return res;
    }

    /**
     * 构造请求体
     * @param content
     * @return
     */
    private static ChatGptRequestModel  builderChatGptRequestModel(String content) {
        MessageModel messageModel = MessageModel.builder().role("user").content(content).build();
        List<MessageModel> list = new ArrayList<>();
        list.add(messageModel);
        return ChatGptRequestModel.builder()
                .model("gpt-3.5-turbo")
                .messages(list)
                .build()
                ;

    }
    public static void main(String[] args) {
        OpeAI openai = new OpeAI();
        openai.chat("你好");
    }
}

